package rexsee.device;

import java.io.File;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;
import android.content.ContentValues;
import android.media.RingtoneManager;
import android.net.Uri;
import android.provider.MediaStore;

public class RexseeRingtone implements JavascriptInterface {

	public static final String INTERFACE_NAME = "Ringtone";

	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return this;
	}

	private final Browser mBrowser;

	public RexseeRingtone(Browser browser) {
		mBrowser = browser;
	}

	public boolean setRingtone(String name, String path) {

		if (!path.toLowerCase().startsWith("file://")) {
			mBrowser.exception(getInterfaceName(), "Invalid path.");
			return false;
		}
		if (!path.toLowerCase().endsWith(".mp3")) {
			mBrowser.exception(getInterfaceName(), "Invalid file type, please use .mp3 file.");
			return false;
		}
		File file = new File(Uri.parse(path).getPath());
		if (!file.exists()) {
			mBrowser.exception(getInterfaceName(), "The specified file does not exists.");
			return false;
		}

		try {
			ContentValues values = new ContentValues();
			values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
			values.put(MediaStore.MediaColumns.TITLE, name);
			values.put(MediaStore.MediaColumns.SIZE, file.length());
			values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
			values.put(MediaStore.Audio.Media.ARTIST, "Unknown");
			values.put(MediaStore.Audio.Media.DURATION, 230);
			values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
			values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
			values.put(MediaStore.Audio.Media.IS_ALARM, false);
			values.put(MediaStore.Audio.Media.IS_MUSIC, false);

			Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
			Uri newUri = mBrowser.getContext().getContentResolver().insert(uri, values);
			if (newUri == null) {
				mBrowser.exception(getInterfaceName(), "Error on inserting the data to the database.");
				return false;
			}
			RingtoneManager.setActualDefaultRingtoneUri(mBrowser.getContext(), RingtoneManager.TYPE_RINGTONE, newUri);
			return true;
		} catch (Exception e) {
			mBrowser.exception(getInterfaceName(), e);
			return false;
		}

	}

}
